// 博客管理功能
class BlogManager {
    constructor() {
        this.currentSection = 'articles';
        this.currentTab = 'all';
        this.editingCategoryId = null;
        this.editingColumnId = null;
        this.parentCategoriesLoaded = false;
        this.categoryOptionsLoaded = false;
        this.init().catch(error => {
            console.error('博客管理器初始化失败:', error);
        });
    }

    async init() {
        this.bindEvents();
        
        // 先加载博客统计数据
        await this.loadBlogStats();
        
        // 先加载文章（包括本地草稿），即使API失败也能显示内容
        await this.loadArticles();
        
        // 异步加载分类和栏目，即使失败也不影响主要功能
        this.loadCategories().catch(error => {
            console.warn('加载分类失败，但不影响主要功能:', error);
        });
        
        this.loadColumns().catch(error => {
            console.warn('加载栏目失败，但不影响主要功能:', error);
        });
    }

    bindEvents() {
        // 绑定分类名称输入事件，自动生成slug
        document.getElementById('category-name')?.addEventListener('input', (e) => {
            const slugInput = document.getElementById('category-slug');
            if (slugInput && !slugInput.value) {
                slugInput.value = this.generateSlug(e.target.value);
            }
        });

        // 绑定栏目名称输入事件，自动生成slug
        document.getElementById('column-name')?.addEventListener('input', (e) => {
            const slugInput = document.getElementById('column-slug');
            if (slugInput && !slugInput.value) {
                slugInput.value = this.generateSlug(e.target.value);
            }
        });
    }

    // 加载博客统计数据
    async loadBlogStats() {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.get('/blog-analytics/overview');
            
            if (response.success) {
                this.updateBlogStatsUI(response.data);
            } else {
                console.warn('获取博客统计数据失败:', response.message);
            }
        } catch (error) {
            console.error('加载博客统计数据失败:', error);
            // 即使失败也显示默认数据
            this.updateBlogStatsUI({
                total_articles: 0,
                total_views: 0,
                total_likes: 0,
                total_comments: 0,
                recent_stats: {}
            });
        }
    }

    // 更新博客统计UI
    updateBlogStatsUI(stats) {
        const elements = {
            'total-articles': stats.total_articles,
            'total-views': this.formatNumber(stats.total_views),
            'total-likes': this.formatNumber(stats.total_likes),
            'total-comments': this.formatNumber(stats.total_comments),
            'recent-articles': stats.recent_stats?.recent_articles || 0,
            'recent-views': this.formatNumber(stats.recent_stats?.recent_views || 0),
            'recent-likes': this.formatNumber(stats.recent_stats?.recent_likes || 0),
            'recent-comments': this.formatNumber(stats.recent_stats?.recent_comments || 0)
        };

        Object.entries(elements).forEach(([id, value]) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = value;
            }
        });
    }

    // 格式化数字显示
    formatNumber(num) {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    }

    // 刷新博客统计数据
    refreshBlogStats() {
        this.loadBlogStats();
    }

    // 生成URL友好的slug
    generateSlug(text) {
        return text
            .toLowerCase()
            .replace(/\s+/g, '-')
            .replace(/[^\w\-]+/g, '')
            .replace(/\-\-+/g, '-')
            .replace(/^\-+/, '')
            .replace(/\-+$/, '');
    }

    // 显示/隐藏不同部分
    showSection(section, event) {
        // 更新侧边栏激活状态
        document.querySelectorAll('.sidebar a').forEach(link => {
            link.classList.remove('active');
        });
        event.target.classList.add('active');

        // 更新内容区域
        document.querySelectorAll('.section').forEach(sectionEl => {
            sectionEl.classList.remove('active');
        });
        document.getElementById(`${section}-section`).classList.add('active');

        this.currentSection = section;
    }

    // 显示/隐藏标签页
    showTab(tab, event) {
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(tab).classList.add('active');

        this.currentTab = tab;
        this.loadArticles();
    }

    // 加载文章列表
    async loadArticles() {
        try {
            let status = '';
            switch (this.currentTab) {
                case 'drafts':
                    status = 'draft';
                    break;
                case 'trash':
                    status = 'deleted';
                    break;
                default:
                    status = 'published';
            }

            // 如果是草稿箱，先显示本地草稿，然后尝试从API加载
            if (this.currentTab === 'drafts') {
                const localDrafts = this.loadDraftsFromLocalStorage();
                this.renderArticles(localDrafts, this.currentTab);
                
                // 异步加载服务器草稿，加载完成后更新显示
                this.loadServerDrafts().then(serverDrafts => {
                    if (serverDrafts.length > 0) {
                        const allDrafts = [...localDrafts, ...serverDrafts];
                        this.renderArticles(allDrafts, this.currentTab);
                    }
                }).catch(error => {
                    console.warn('加载服务器草稿失败:', error);
                    // 服务器草稿加载失败不影响本地草稿显示，不显示错误消息
                });
                return;
            }

            // 其他标签页直接从API加载
            try {
                const response = await apiClient.get(`/api/articles?status=${status}&limit=20`);
                
                if (response.success) {
                    this.renderArticles(response.data.articles || [], this.currentTab);
                } else {
                    this.showMessage('加载文章失败', 'error');
                }
            } catch (error) {
                console.error('API调用失败:', error);
                this.showMessage('加载文章失败', 'error');
            }
        } catch (error) {
            console.error('加载文章失败:', error);
            // 只在非草稿箱标签页显示错误消息
            if (this.currentTab !== 'drafts') {
                this.showMessage('加载文章失败', 'error');
            }
        }
    }

    // 从服务器加载草稿
    async loadServerDrafts() {
        try {
            const response = await apiClient.get('/api/articles?status=draft&limit=20');
            if (response.success) {
                return response.data.articles || [];
            }
        } catch (error) {
            console.warn('加载服务器草稿失败:', error);
        }
        return [];
    }

    // 从本地存储加载草稿
    loadDraftsFromLocalStorage() {
        try {
            const savedDraft = localStorage.getItem('currentDraft');
            if (savedDraft) {
                const draft = JSON.parse(savedDraft);
                // 检查草稿是否有内容
                if (draft.title || draft.content) {
                    // 将本地草稿转换为文章格式
                    return [{
                        id: 'local-draft',
                        title: draft.title || '无标题草稿',
                        content: draft.content || '',
                        status: 'draft',
                        createdAt: draft.lastModified || new Date().toISOString(),
                        updatedAt: draft.lastModified || new Date().toISOString(),
                        isLocalDraft: true // 标记为本地草稿
                    }];
                }
            }
        } catch (error) {
            console.error('加载本地草稿失败:', error);
        }
        return [];
    }

    // 渲染文章列表
    renderArticles(articles, tab) {
        // 特殊处理草稿箱的容器ID
        const containerId = tab === 'drafts' ? 'draft-list' : `${tab}-list`;
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`找不到容器: ${containerId}`);
            return;
        }

        if (articles.length === 0) {
            container.innerHTML = '<div class="no-data">暂无文章</div>';
            return;
        }

        container.innerHTML = articles.map(article => {
            // 处理本地草稿的特殊显示
            const isLocalDraft = article.isLocalDraft;
            const articleId = isLocalDraft ? 'local-draft' : article.id;
            const categoryName = isLocalDraft ? '未分类' : this.getCategoryName(article.category);
            const createdAt = isLocalDraft ? new Date(article.createdAt).toLocaleDateString('zh-CN') : this.formatDate(article.createdAt);
            const excerpt = isLocalDraft ? 
                (article.content ? this.escapeHtml(article.content.substring(0, 100)) + '...' : '暂无内容') : 
                this.escapeHtml(article.content.substring(0, 100)) + '...';

            return `
            <div class="article-item ${article.status === 'deleted' ? 'deleted' : ''} ${isLocalDraft ? 'local-draft' : ''}">
                <h3>${this.escapeHtml(article.title)} ${isLocalDraft ? '<span style="color: #faad14; font-size: 12px;">(本地草稿)</span>' : ''}</h3>
                <p class="article-meta">${categoryName} | ${createdAt} | ${this.getStatusText(article.status)}</p>
                <p class="article-excerpt">${excerpt}</p>
                <div class="article-actions">
                    ${tab === 'trash' ? 
                        `<button onclick="blogManager.restoreArticle('${articleId}')">恢复</button>
                         <button onclick="blogManager.permanentDeleteArticle('${articleId}')">永久删除</button>` :
                        `<button onclick="blogManager.editArticle('${articleId}')">编辑</button>
                         ${article.status === 'draft' ? 
                            `<button onclick="blogManager.publishArticle('${articleId}')">发布</button>` : 
                            `<button onclick="blogManager.deleteArticle('${articleId}')">删除</button>`}`}
                </div>
            </div>
            `;
        }).join('');
    }

    // 加载分类列表
    async loadCategories() {
        try {
            const response = await apiClient.get('/api/blog-categories');
            
            if (response.success) {
                this.categories = response.data.categories;
                this.renderCategories(this.categories);
            } else {
                this.showMessage('加载分类失败', 'error');
            }
        } catch (error) {
            console.error('加载分类失败:', error);
            this.showMessage('加载分类失败', 'error');
        }
    }

    // 渲染分类列表
    renderCategories(categories) {
        const container = document.getElementById('categories-grid');
        if (!container) return;

        if (categories.length === 0) {
            container.innerHTML = '<div class="no-data">暂无分类</div>';
            return;
        }

        container.innerHTML = categories.map(category => `
            <div class="category-card">
                <div class="category-header">
                    <h4 class="category-name">${this.escapeHtml(category.name)}</h4>
                    <div class="category-actions">
                        <button onclick="blogManager.editCategory(${category.id})">编辑</button>
                        <button onclick="blogManager.deleteCategory(${category.id})">删除</button>
                    </div>
                </div>
                <p class="category-description">${this.escapeHtml(category.description || '暂无描述')}</p>
                <div class="category-stats">
                    <span class="category-stat"><i class="fas fa-file"></i> 文章数: 0</span>
                    <span class="category-stat"><i class="fas fa-folder"></i> 子分类: 0</span>
                </div>
            </div>
        `).join('');
    }

    // 加载栏目列表
    async loadColumns() {
        try {
            const response = await apiClient.get('/api/blog-columns');
            
            if (response.success) {
                this.columns = response.data.columns;
                this.renderColumns(this.columns);
            } else {
                this.showMessage('加载栏目失败', 'error');
            }
        } catch (error) {
            console.error('加载栏目失败:', error);
            this.showMessage('加载栏目失败', 'error');
        }
    }

    // 渲染栏目列表
    renderColumns(columns) {
        const container = document.getElementById('columns-grid');
        if (!container) return;

        if (columns.length === 0) {
            container.innerHTML = '<div class="no-data">暂无栏目</div>';
            return;
        }

        container.innerHTML = columns.map(column => `
            <div class="column-card">
                <div class="column-header">
                    <h4 class="column-name">${this.escapeHtml(column.name)}</h4>
                    <div class="column-actions">
                        <button onclick="blogManager.editColumn(${column.id})">编辑</button>
                        <button onclick="blogManager.deleteColumn(${column.id})">删除</button>
                    </div>
                </div>
                <p class="column-description">${this.escapeHtml(column.description || '暂无描述')}</p>
                <div class="column-stats">
                    <span class="column-stat"><i class="fas fa-folder"></i> 包含分类: ${column.categories.length}</span>
                </div>
            </div>
        `).join('');
    }

    // 显示分类编辑模态框
    async showCategoryModal(categoryId = null) {
        this.editingCategoryId = categoryId;
        const modal = document.getElementById('category-modal');
        const title = document.getElementById('category-modal-title');
        const form = document.getElementById('category-form');
        
        title.textContent = categoryId ? '编辑分类' : '新建分类';
        form.reset();
        
        // 预加载父分类选项（如果还没有加载过）
        if (!this.parentCategoriesLoaded) {
            await this.loadParentCategories();
            this.parentCategoriesLoaded = true;
        }
        
        if (categoryId) {
            await this.loadCategoryData(categoryId);
        }
        
        // 显示模态框并添加动画
        modal.style.display = 'block';
        setTimeout(() => {
            modal.classList.add('active');
        }, 10);
    }

    // 加载父分类选项
    async loadParentCategories() {
        try {
            const response = await apiClient.get('/api/blog-categories');
            const select = document.getElementById('category-parent');
            
            if (response.success) {
                select.innerHTML = '<option value="">无父分类</option>' + 
                    response.data.categories.map(cat => 
                        `<option value="${cat.id}">${this.escapeHtml(cat.name)}</option>`
                    ).join('');
            }
        } catch (error) {
            console.error('加载父分类失败:', error);
        }
    }

    // 加载分类数据
    async loadCategoryData(categoryId) {
        try {
            const response = await apiClient.get(`/api/blog-categories/${categoryId}`);
            
            if (response.success) {
                const category = response.data;
                document.getElementById('category-name').value = category.name;
                document.getElementById('category-slug').value = category.slug;
                document.getElementById('category-description').value = category.description || '';
                document.getElementById('category-parent').value = category.parentId || '';
                document.getElementById('category-sort').value = category.sortOrder;
            }
        } catch (error) {
            console.error('加载分类数据失败:', error);
        }
    }

    // 保存分类
    async saveCategory() {
        try {
            const formData = {
                name: document.getElementById('category-name').value.trim(),
                slug: document.getElementById('category-slug').value.trim(),
                description: document.getElementById('category-description').value.trim(),
                parentId: document.getElementById('category-parent').value || null,
                sortOrder: parseInt(document.getElementById('category-sort').value) || 0
            };

            if (!formData.name) {
                this.showMessage('分类名称不能为空', 'error');
                return;
            }

            let response;
            if (this.editingCategoryId) {
                response = await apiClient.put(`/api/blog-categories/${this.editingCategoryId}`, formData);
            } else {
                response = await apiClient.post('/api/blog-categories', formData);
            }

            if (response.success) {
                this.showMessage(response.message, 'success');
                this.closeCategoryModal();
                this.loadCategories();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('保存分类失败:', error);
            this.showMessage('保存分类失败', 'error');
        }
    }

    // 关闭分类模态框
    closeCategoryModal() {
        const modal = document.getElementById('category-modal');
        modal.classList.remove('active');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
        this.editingCategoryId = null;
    }

    // 编辑分类
    editCategory(categoryId) {
        this.showCategoryModal(categoryId);
    }

    // 删除分类
    async deleteCategory(categoryId) {
        if (!confirm('确定要删除这个分类吗？')) return;

        try {
            const response = await apiClient.delete(`/api/blog-categories/${categoryId}`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadCategories();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('删除分类失败:', error);
            this.showMessage('删除分类失败', 'error');
        }
    }

    // 显示栏目编辑模态框
    async showColumnModal(columnId = null) {
        this.editingColumnId = columnId;
        const modal = document.getElementById('column-modal');
        const title = document.getElementById('column-modal-title');
        
        title.textContent = columnId ? '编辑栏目' : '新建栏目';
        document.getElementById('column-form').reset();
        
        // 预加载分类选项（如果还没有加载过）
        if (!this.categoryOptionsLoaded) {
            await this.loadCategoryOptions();
            this.categoryOptionsLoaded = true;
        }
        
        if (columnId) {
            await this.loadColumnData(columnId);
        }
        
        // 显示模态框并添加动画
        modal.style.display = 'block';
        setTimeout(() => {
            modal.classList.add('active');
        }, 10);
    }

    // 加载分类选项
    async loadCategoryOptions() {
        try {
            const response = await apiClient.get('/api/blog-categories');
            const select = document.getElementById('column-categories');
            
            if (response.success) {
                select.innerHTML = response.data.categories.map(cat => 
                    `<option value="${cat.id}">${this.escapeHtml(cat.name)}</option>`
                ).join('');
            }
        } catch (error) {
            console.error('加载分类选项失败:', error);
        }
    }

    // 加载栏目数据
    async loadColumnData(columnId) {
        try {
            const response = await apiClient.get(`/api/blog-columns/${columnId}`);
            
            if (response.success) {
                const column = response.data;
                document.getElementById('column-name').value = column.name;
                document.getElementById('column-slug').value = column.slug;
                document.getElementById('column-description').value = column.description || '';
                document.getElementById('column-sort').value = column.sort_order;
                
                // 设置选中的分类
                const categorySelect = document.getElementById('column-categories');
                Array.from(categorySelect.options).forEach(option => {
                    option.selected = column.categories.some(cat => cat.id === parseInt(option.value));
                });
            }
        } catch (error) {
            console.error('加载栏目数据失败:', error);
        }
    }

    // 保存栏目
    async saveColumn() {
        try {
            const formData = {
                name: document.getElementById('column-name').value.trim(),
                slug: document.getElementById('column-slug').value.trim(),
                description: document.getElementById('column-description').value.trim(),
                sortOrder: parseInt(document.getElementById('column-sort').value) || 0
            };

            // 获取选中的分类
            const categorySelect = document.getElementById('column-categories');
            const selectedCategories = Array.from(categorySelect.selectedOptions).map(option => parseInt(option.value));
            formData.categories = selectedCategories;

            if (!formData.name) {
                this.showMessage('栏目名称不能为空', 'error');
                return;
            }

            let response;
            if (this.editingColumnId) {
                response = await apiClient.put(`/api/blog-columns/${this.editingColumnId}`, formData);
            } else {
                response = await apiClient.post('/api/blog-columns', formData);
            }

            if (response.success) {
                this.showMessage(response.message, 'success');
                this.closeColumnModal();
                this.loadColumns();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('保存栏目失败:', error);
            this.showMessage('保存栏目失败', 'error');
        }
    }

    // 关闭栏目模态框
    closeColumnModal() {
        const modal = document.getElementById('column-modal');
        modal.classList.remove('active');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
        this.editingColumnId = null;
    }

    // 编辑栏目
    editColumn(columnId) {
        this.showColumnModal(columnId);
    }

    // 删除栏目
    async deleteColumn(columnId) {
        if (!confirm('确定要删除这个栏目吗？')) return;

        try {
            const response = await apiClient.delete(`/api/blog-columns/${columnId}`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadColumns();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('删除栏目失败:', error);
            this.showMessage('删除栏目失败', 'error');
        }
    }

    // 文章操作
    editArticle(articleId) {
        // 处理本地草稿
        if (articleId === 'local-draft') {
            window.location.href = 'editor.html';
            return;
        }
        window.location.href = `editor.html?articleId=${articleId}`;
    }

    async publishArticle(articleId) {
        // 处理本地草稿的发布
        if (articleId === 'local-draft') {
            if (!confirm('确定要发布这个本地草稿吗？发布后草稿将被保存到服务器。')) return;
            
            try {
                const savedDraft = localStorage.getItem('currentDraft');
                if (savedDraft) {
                    const draft = JSON.parse(savedDraft);
                    
                    // 调用API发布文章
                    const response = await apiClient.post('/api/articles', {
                        title: draft.title,
                        content: draft.content,
                        status: 'published'
                    });
                    
                    if (response.success) {
                        // 清除本地草稿
                        localStorage.removeItem('currentDraft');
                        this.showMessage('文章发布成功', 'success');
                        this.loadArticles();
                    } else {
                        this.showMessage('发布失败：' + response.message, 'error');
                    }
                } else {
                    this.showMessage('未找到草稿数据', 'error');
                }
            } catch (error) {
                console.error('发布本地草稿失败:', error);
                this.showMessage('发布失败', 'error');
            }
            return;
        }

        try {
            const response = await apiClient.put(`/api/articles/${articleId}/publish`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('发布文章失败:', error);
            this.showMessage('发布文章失败', 'error');
        }
    }

    async deleteArticle(articleId) {
        // 处理本地草稿的删除
        if (articleId === 'local-draft') {
            if (!confirm('确定要删除这个本地草稿吗？此操作不可恢复！')) return;
            
            localStorage.removeItem('currentDraft');
            this.showMessage('本地草稿已删除', 'success');
            this.loadArticles();
            return;
        }

        if (!confirm('确定要删除这篇文章吗？')) return;

        try {
            const response = await apiClient.delete(`/api/articles/${articleId}`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('删除文章失败:', error);
            this.showMessage('删除文章失败', 'error');
        }
    }

    async publishArticle(articleId) {
        try {
            const response = await apiClient.put(`/api/articles/${articleId}/publish`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('发布文章失败:', error);
            this.showMessage('发布文章失败', 'error');
        }
    }

    async deleteArticle(articleId) {
        if (!confirm('确定要删除这篇文章吗？')) return;

        try {
            const response = await apiClient.delete(`/api/articles/${articleId}`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('删除文章失败:', error);
            this.showMessage('删除文章失败', 'error');
        }
    }

    async restoreArticle(articleId) {
        try {
            const response = await apiClient.put(`/api/articles/${articleId}/restore`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('恢复文章失败:', error);
            this.showMessage('恢复文章失败', 'error');
        }
    }

    async permanentDeleteArticle(articleId) {
        if (!confirm('确定要永久删除这篇文章吗？此操作不可恢复！')) return;

        try {
            const response = await apiClient.delete(`/api/articles/${articleId}/permanent`);
            
            if (response.success) {
                this.showMessage(response.message, 'success');
                this.loadArticles();
            } else {
                this.showMessage(response.message, 'error');
            }
        } catch (error) {
            console.error('永久删除文章失败:', error);
            this.showMessage('永久删除文章失败', 'error');
        }
    }

    // 工具方法
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    formatDate(dateString) {
        return new Date(dateString).toLocaleDateString('zh-CN');
    }

    getStatusText(status) {
        const statusMap = {
            'published': '已发布',
            'draft': '草稿',
            'deleted': '已删除'
        };
        return statusMap[status] || status;
    }

    getCategoryName(categoryId) {
        // 从分类列表中查找分类名称
        const categories = this.categories || [];
        const category = categories.find(cat => cat.id === categoryId);
        return category ? category.name : `分类${categoryId}`;
    }

    showMessage(message, type = 'info') {
        const alert = document.createElement('div');
        alert.className = `alert alert-${type}`;
        alert.textContent = message;
        alert.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            z-index: 1000;
            background: ${type === 'error' ? '#ff4d4f' : type === 'success' ? '#52c41a' : '#1890ff'};
        `;
        document.body.appendChild(alert);
        setTimeout(() => alert.remove(), 3000);
    }
}

// 全局函数
function showSection(section, event) {
    blogManager.showSection(section, event);
}

function showTab(tab, event) {
    blogManager.showTab(tab, event);
}

function showCategoryModal(categoryId = null) {
    blogManager.showCategoryModal(categoryId);
}

function closeCategoryModal() {
    blogManager.closeCategoryModal();
}

function saveCategory() {
    blogManager.saveCategory();
}

function showColumnModal(columnId = null) {
    blogManager.showColumnModal(columnId);
}

function closeColumnModal() {
    blogManager.closeColumnModal();
}

function saveColumn() {
    blogManager.saveColumn();
}

// 点击模态框外部关闭
window.addEventListener('click', (event) => {
    const categoryModal = document.getElementById('category-modal');
    const columnModal = document.getElementById('column-modal');
    const replyModal = document.getElementById('reply-modal');
    
    if (event.target === categoryModal) {
        closeCategoryModal();
    }
    if (event.target === columnModal) {
        closeColumnModal();
    }
    if (event.target === replyModal) {
        closeReplyModal();
    }
});

// 评论管理功能
class CommentManager {
    constructor() {
        this.currentCommentTab = 'all';
        this.currentPage = 1;
        this.selectedComments = new Set();
        this.init();
    }

    init() {
        this.bindCommentEvents();
    }

    bindCommentEvents() {
        // 绑定评论选择事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('comment-checkbox')) {
                this.toggleCommentSelection(e.target.value, e.target.checked);
            }
        });
    }

    // 显示评论标签页
    showCommentTab(tab, event) {
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        this.currentCommentTab = tab;
        this.currentPage = 1;
        this.selectedComments.clear();
        this.updateBatchToolbar();
        this.loadComments();
    }

    // 加载评论列表
    async loadComments() {
        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                limit: 10
            });

            if (this.currentCommentTab !== 'all') {
                params.append('status', this.currentCommentTab);
            }

            const response = await apiClient.get(`/api/comments?${params}`);
            
            if (response.success) {
                this.renderComments(response.data.comments);
                this.renderPagination(response.data.pagination);
            } else {
                this.showMessage('加载评论失败', 'error');
            }
        } catch (error) {
            console.error('加载评论失败:', error);
            this.showMessage('加载评论失败', 'error');
        }
    }

    // 渲染评论列表
    renderComments(comments) {
        const container = document.getElementById('comments-container');
        if (!container) return;

        if (comments.length === 0) {
            container.innerHTML = '<div class="no-data">暂无评论</div>';
            return;
        }

        container.innerHTML = comments.map(comment => `
            <div class="comment-item ${this.selectedComments.has(comment.id) ? 'selected' : ''}">
                <input type="checkbox" class="comment-checkbox" value="${comment.id}" 
                       ${this.selectedComments.has(comment.id) ? 'checked' : ''}>
                
                <div class="comment-content">
                    <div class="comment-header">
                        <div>
                            <span class="comment-author">${this.escapeHtml(comment.authorName)}</span>
                            <span class="comment-email">${this.escapeHtml(comment.authorEmail)}</span>
                            ${comment.article ? 
                                `<a href="#" class="comment-article" onclick="viewArticle(${comment.article.id})">
                                    《${this.escapeHtml(comment.article.title)}》
                                </a>` : ''
                            }
                        </div>
                        <span class="comment-status status-${comment.status}">
                            ${this.getStatusText(comment.status)}
                        </span>
                    </div>
                    
                    <div class="comment-text">
                        ${this.escapeHtml(comment.content)}
                    </div>
                    
                    <div class="comment-meta">
                        <span>${this.formatDate(comment.createdAt)}</span>
                        <span>IP: ${comment.ipAddress || '未知'}</span>
                    </div>
                    
                    <div class="comment-actions">
                        ${comment.status === 'pending' ? 
                            `<button class="btn-approve" onclick="approveComment(${comment.id})">通过</button>
                             <button class="btn-reject" onclick="rejectComment(${comment.id})">拒绝</button>` : ''
                        }
                        ${comment.status === 'approved' ? 
                            `<button class="btn-feature" onclick="featureComment(${comment.id})">设为精选</button>` : ''
                        }
                        ${comment.status === 'featured' ? 
                            `<button class="btn-feature" onclick="unfeatureComment(${comment.id})">取消精选</button>` : ''
                        }
                        <button class="btn-reply" onclick="showReplyModal(${comment.id})">回复</button>
                        <button onclick="deleteComment(${comment.id})">删除</button>
                    </div>
                </div>
            </div>
        `).join('');
    }

    // 渲染分页
    renderPagination(pagination) {
        const container = document.getElementById('comment-pagination');
        if (!container || !pagination) return;

        const { page, pages } = pagination;
        
        let paginationHTML = `<div class="pagination-info">
            第 ${page} 页，共 ${pages} 页，${pagination.total} 条评论
        </div>`;

        if (pages > 1) {
            paginationHTML += '<div class="pagination-buttons">';
            
            // 上一页
            paginationHTML += `<button onclick="goToCommentPage(${page - 1})" ${page <= 1 ? 'disabled' : ''}>
                上一页
            </button>`;

            // 页码
            for (let i = 1; i <= pages; i++) {
                if (i === 1 || i === pages || (i >= page - 2 && i <= page + 2)) {
                    paginationHTML += `<button onclick="goToCommentPage(${i})" ${i === page ? 'class="active"' : ''}>
                        ${i}
                    </button>`;
                } else if (i === page - 3 || i === page + 3) {
                    paginationHTML += '<span>...</span>';
                }
            }

            // 下一页
            paginationHTML += `<button onclick="goToCommentPage(${page + 1})" ${page >= pages ? 'disabled' : ''}>
                下一页
            </button>`;

            paginationHTML += '</div>';
        }

        container.innerHTML = paginationHTML;
    }

    // 切换评论选择
    toggleCommentSelection(commentId, selected) {
        if (selected) {
            this.selectedComments.add(parseInt(commentId));
        } else {
            this.selectedComments.delete(parseInt(commentId));
        }
        this.updateBatchToolbar();
    }

    // 更新批量操作工具栏
    updateBatchToolbar() {
        const toolbar = document.getElementById('comment-batch-toolbar');
        const countSpan = document.getElementById('selected-count');
        
        if (this.selectedComments.size > 0) {
            toolbar.style.display = 'flex';
            countSpan.textContent = `已选择 ${this.selectedComments.size} 条评论`;
        } else {
            toolbar.style.display = 'none';
        }
    }

    // 清空选择
    clearSelection() {
        this.selectedComments.clear();
        this.updateBatchToolbar();
        
        // 更新UI
        document.querySelectorAll('.comment-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        document.querySelectorAll('.comment-item').forEach(item => {
            item.classList.remove('selected');
        });
    }

    // 获取状态文本
    getStatusText(status) {
        const statusMap = {
            'pending': '待审核',
            'approved': '已通过',
            'rejected': '已拒绝',
            'featured': '精选'
        };
        return statusMap[status] || status;
    }

    // 显示消息
    showMessage(message, type = 'info') {
        // 这里可以添加消息提示功能
        console.log(`[${type}] ${message}`);
    }

    // HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 格式化日期
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
}

// 全局函数
function showCommentTab(tab, event) {
    commentManager.showCommentTab(tab, event);
}

function goToCommentPage(page) {
    commentManager.currentPage = page;
    commentManager.loadComments();
}

async function approveComment(commentId) {
    try {
        const response = await apiClient.put(`/api/comments/${commentId}/status`, {
            status: 'approved'
        });
        
        if (response.success) {
            commentManager.showMessage('评论已通过', 'success');
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('通过评论失败:', error);
        commentManager.showMessage('操作失败', 'error');
    }
}

async function rejectComment(commentId) {
    try {
        const response = await apiClient.put(`/api/comments/${commentId}/status`, {
            status: 'rejected'
        });
        
        if (response.success) {
            commentManager.showMessage('评论已拒绝', 'success');
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('拒绝评论失败:', error);
        commentManager.showMessage('操作失败', 'error');
    }
}

async function featureComment(commentId) {
    try {
        const response = await apiClient.put(`/api/comments/${commentId}/featured`, {
            featured: true
        });
        
        if (response.success) {
            commentManager.showMessage('评论已设为精选', 'success');
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('设为精选失败:', error);
        commentManager.showMessage('操作失败', 'error');
    }
}

async function unfeatureComment(commentId) {
    try {
        const response = await apiClient.put(`/api/comments/${commentId}/featured`, {
            featured: false
        });
        
        if (response.success) {
            commentManager.showMessage('评论已取消精选', 'success');
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('取消精选失败:', error);
        commentManager.showMessage('操作失败', 'error');
    }
}

async function deleteComment(commentId) {
    if (!confirm('确定要删除这条评论吗？')) return;
    
    try {
        const response = await apiClient.delete(`/api/comments/${commentId}`);
        
        if (response.success) {
            commentManager.showMessage('评论已删除', 'success');
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('删除评论失败:', error);
        commentManager.showMessage('删除失败', 'error');
    }
}

function showReplyModal(commentId) {
    // 这里可以添加回复评论的模态框
    console.log('回复评论:', commentId);
    alert('回复评论功能待实现');
}

function closeReplyModal() {
    // 关闭回复模态框
}

// 批量操作函数
async function batchApproveComments() {
    await batchCommentAction('approve');
}

async function batchRejectComments() {
    await batchCommentAction('reject');
}

async function batchFeatureComments() {
    await batchCommentAction('feature');
}

async function batchUnfeatureComments() {
    await batchCommentAction('unfeature');
}

async function batchDeleteComments() {
    if (!confirm(`确定要删除选中的 ${commentManager.selectedComments.size} 条评论吗？`)) return;
    await batchCommentAction('delete');
}

async function batchCommentAction(action) {
    if (commentManager.selectedComments.size === 0) {
        commentManager.showMessage('请先选择评论', 'warning');
        return;
    }

    try {
        const response = await apiClient.post('/api/comments/batch', {
            ids: Array.from(commentManager.selectedComments),
            action: action
        });
        
        if (response.success) {
            commentManager.showMessage(`批量操作成功，影响 ${response.data.updatedCount} 条评论`, 'success');
            commentManager.clearSelection();
            commentManager.loadComments();
        }
    } catch (error) {
        console.error('批量操作失败:', error);
        commentManager.showMessage('批量操作失败', 'error');
    }
}

function clearCommentSelection() {
    commentManager.clearSelection();
}

function viewArticle(articleId) {
    // 这里可以跳转到文章详情页
    console.log('查看文章:', articleId);
}

// ==================== 多语言管理功能 ====================

// 博客多语言管理器
class BlogI18nManager {
    constructor() {
        this.i18nConfig = null;
        this.blogI18nStatus = {};
    }

    // 初始化多语言管理器
    async init() {
        await this.loadI18nConfig();
        await this.loadBlogI18nStatus();
        this.renderSupportedLanguages();
        this.renderBlogI18nStatus();
    }

    // 加载多语言配置
    async loadI18nConfig() {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.get('/api/blog-i18n/config');
            
            if (response.success) {
                this.i18nConfig = response.data;
                this.updateConfigUI();
            }
        } catch (error) {
            console.error('加载多语言配置失败:', error);
        }
    }

    // 加载博客多语言状态
    async loadBlogI18nStatus() {
        try {
            const apiClient = new ApiClient();
            // 获取所有博客的多语言状态
            const blogs = await this.getAllBlogs();
            
            for (const blog of blogs) {
                const response = await apiClient.get(`/api/blog-i18n/status/${blog._id}`);
                if (response.success) {
                    this.blogI18nStatus[blog._id] = response.data;
                }
            }
        } catch (error) {
            console.error('加载博客多语言状态失败:', error);
        }
    }

    // 获取所有博客
    async getAllBlogs() {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.get('/api/blogs');
            return response.success ? response.data : [];
        } catch (error) {
            console.error('获取博客列表失败:', error);
            return [];
        }
    }

    // 更新配置UI
    updateConfigUI() {
        if (!this.i18nConfig) return;

        // 更新启用状态
        const enabledCheckbox = document.getElementById('i18n-enabled');
        if (enabledCheckbox) {
            enabledCheckbox.checked = this.i18nConfig.enabled;
        }

        // 更新默认语言
        const defaultLanguageSelect = document.getElementById('default-language');
        if (defaultLanguageSelect) {
            defaultLanguageSelect.value = this.i18nConfig.defaultLanguage;
        }

        // 更新翻译服务
        const translationProviderSelect = document.getElementById('translation-provider');
        if (translationProviderSelect) {
            translationProviderSelect.value = this.i18nConfig.translationProvider;
        }
    }

    // 渲染支持的语言列表
    renderSupportedLanguages() {
        const container = document.getElementById('supported-languages-list');
        if (!container || !this.i18nConfig) return;

        const languages = this.i18nConfig.supportedLanguages || [];
        
        container.innerHTML = languages.map(lang => `
            <div class="language-item">
                <div class="language-info">
                    <span class="flag">${this.getFlagEmoji(lang.code)}</span>
                    <span class="language-name">${lang.name}</span>
                    <span class="language-code">${lang.code}</span>
                </div>
                <div class="language-controls">
                    <label class="toggle-switch">
                        <input type="checkbox" ${lang.enabled ? 'checked' : ''} 
                               onchange="BlogManager.toggleLanguageEnabled('${lang.code}', this.checked)">
                        <span class="slider"></span>
                    </label>
                    <label class="auto-translate-toggle">
                        <input type="checkbox" ${lang.autoTranslate ? 'checked' : ''} 
                               onchange="BlogManager.toggleAutoTranslate('${lang.code}', this.checked)"
                               ${!lang.enabled ? 'disabled' : ''}>
                        自动翻译
                    </label>
                </div>
            </div>
        `).join('');
    }

    // 渲染博客多语言状态
    renderBlogI18nStatus() {
        const container = document.getElementById('blog-i18n-status');
        if (!container) return;

        const statusList = Object.values(this.blogI18nStatus);
        
        if (statusList.length === 0) {
            container.innerHTML = '<p>暂无博客多语言数据</p>';
            return;
        }

        container.innerHTML = statusList.map(status => `
            <div class="blog-status-item">
                <div class="blog-title">${status.blogId}</div>
                <div class="progress-bar">
                    <div class="progress-fill" style="width: ${status.progress}%"></div>
                    <span class="progress-text">${status.progress}%</span>
                </div>
                <div class="language-status">
                    ${Object.entries(status.translations || {}).map(([lang, trans]) => `
                        <span class="lang-tag ${trans.status}" title="${lang}: ${trans.status}">
                            ${this.getFlagEmoji(lang)}
                        </span>
                    `).join('')}
                </div>
                <button class="btn btn-sm" onclick="BlogManager.manageBlogI18n('${status.blogId}')">
                    管理
                </button>
            </div>
        `).join('');
    }

    // 获取国旗emoji
    getFlagEmoji(languageCode) {
        const flags = {
            'zh-CN': '🇨🇳',
            'en-US': '🇺🇸', 
            'ja-JP': '🇯🇵',
            'ko-KR': '🇰🇷',
            'fr-FR': '🇫🇷',
            'de-DE': '🇩🇪',
            'es-ES': '🇪🇸',
            'pt-BR': '🇧🇷',
            'ru-RU': '🇷🇺',
            'it-IT': '🇮🇹',
            'nl-NL': '🇳🇱',
            'pl-PL': '🇵🇱',
            'tr-TR': '🇹🇷',
            'vi-VN': '🇻🇳',
            'th-TH': '🇹🇭',
            'ar-SA': '🇸🇦',
            'hi-IN': '🇮🇳'
        };
        return flags[languageCode] || '🌐';
    }

    // 切换多语言启用状态
    async toggleI18nEnabled() {
        const enabled = document.getElementById('i18n-enabled').checked;
        
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.post('/api/blog-i18n/config', {
                ...this.i18nConfig,
                enabled: enabled
            });
            
            if (response.success) {
                this.i18nConfig.enabled = enabled;
                this.showMessage('配置已更新', 'success');
            }
        } catch (error) {
            console.error('更新配置失败:', error);
            this.showMessage('更新失败', 'error');
        }
    }

    // 更新默认语言
    async updateDefaultLanguage() {
        const language = document.getElementById('default-language').value;
        
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.post('/api/blog-i18n/config', {
                ...this.i18nConfig,
                defaultLanguage: language
            });
            
            if (response.success) {
                this.i18nConfig.defaultLanguage = language;
                this.showMessage('默认语言已更新', 'success');
            }
        } catch (error) {
            console.error('更新默认语言失败:', error);
            this.showMessage('更新失败', 'error');
        }
    }

    // 更新翻译服务
    async updateTranslationProvider() {
        const provider = document.getElementById('translation-provider').value;
        
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.post('/api/blog-i18n/config', {
                ...this.i18nConfig,
                translationProvider: provider
            });
            
            if (response.success) {
                this.i18nConfig.translationProvider = provider;
                this.showMessage('翻译服务已更新', 'success');
            }
        } catch (error) {
            console.error('更新翻译服务失败:', error);
            this.showMessage('更新失败', 'error');
        }
    }

    // 切换语言启用状态
    async toggleLanguageEnabled(languageCode, enabled) {
        try {
            const apiClient = new ApiClient();
            const updatedLanguages = this.i18nConfig.supportedLanguages.map(lang => 
                lang.code === languageCode ? { ...lang, enabled } : lang
            );
            
            const response = await apiClient.post('/api/blog-i18n/config', {
                ...this.i18nConfig,
                supportedLanguages: updatedLanguages
            });
            
            if (response.success) {
                this.i18nConfig.supportedLanguages = updatedLanguages;
                this.renderSupportedLanguages();
                this.showMessage('语言设置已更新', 'success');
            }
        } catch (error) {
            console.error('更新语言设置失败:', error);
            this.showMessage('更新失败', 'error');
        }
    }

    // 切换自动翻译
    async toggleAutoTranslate(languageCode, autoTranslate) {
        try {
            const apiClient = new ApiClient();
            const updatedLanguages = this.i18nConfig.supportedLanguages.map(lang => 
                lang.code === languageCode ? { ...lang, autoTranslate } : lang
            );
            
            const response = await apiClient.post('/api/blog-i18n/config', {
                ...this.i18nConfig,
                supportedLanguages: updatedLanguages
            });
            
            if (response.success) {
                this.i18nConfig.supportedLanguages = updatedLanguages;
                this.showMessage('自动翻译设置已更新', 'success');
            }
        } catch (error) {
            console.error('更新自动翻译设置失败:', error);
            this.showMessage('更新失败', 'error');
        }
    }

    // 管理博客多语言
    async manageBlogI18n(blogId) {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.get(`/api/blog-i18n/content/${blogId}`);
            
            if (response.success) {
                this.showBlogI18nModal(blogId, response.data);
            }
        } catch (error) {
            console.error('获取博客多语言内容失败:', error);
            this.showMessage('获取内容失败', 'error');
        }
    }

    // 显示博客多语言管理模态框
    showBlogI18nModal(blogId, content) {
        const modal = document.getElementById('i18n-modal');
        const modalContent = document.getElementById('i18n-modal-content');
        
        modalContent.innerHTML = `
            <div class="blog-i18n-management">
                <h4>博客多语言管理 - ${blogId}</h4>
                <div class="translation-list">
                    ${Object.entries(content.translations || {}).map(([lang, trans]) => `
                        <div class="translation-item">
                            <div class="translation-header">
                                <span class="flag">${this.getFlagEmoji(lang)}</span>
                                <span class="language-name">${this.getLanguageName(lang)}</span>
                                <span class="status-badge ${trans.status}">${trans.status}</span>
                            </div>
                            <div class="translation-content">
                                <div class="translation-title">${trans.title || '无标题'}</div>
                                <div class="translation-preview">${trans.content ? trans.content.substring(0, 100) + '...' : '无内容'}</div>
                            </div>
                            <div class="translation-actions">
                                <button class="btn btn-sm" onclick="BlogManager.editTranslation('${blogId}', '${lang}')">编辑</button>
                                <button class="btn btn-sm" onclick="BlogManager.publishTranslation('${blogId}', '${lang}')">发布</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div class="translation-actions-panel">
                    <button class="btn btn-primary" onclick="BlogManager.translateAll('${blogId}')">一键翻译所有语言</button>
                    <button class="btn btn-success" onclick="BlogManager.publishAll('${blogId}')">发布所有语言版本</button>
                </div>
            </div>
        `;
        
        modal.style.display = 'block';
    }

    // 获取语言名称
    getLanguageName(languageCode) {
        const languages = {
            'zh-CN': '简体中文',
            'en-US': 'English',
            'ja-JP': '日本語', 
            'ko-KR': '한국어'
        };
        return languages[languageCode] || languageCode;
    }

    // 显示消息
    showMessage(message, type = 'info') {
        // 实现消息显示逻辑
        console.log(`[${type}] ${message}`);
    }
}

// 全局多语言管理器实例
let blogI18nManager = new BlogI18nManager();

// ==================== 全局函数 ====================

// 刷新多语言配置
async function refreshI18nConfig() {
    await blogI18nManager.init();
}

// 切换多语言启用状态
function toggleI18nEnabled() {
    blogI18nManager.toggleI18nEnabled();
}

// 更新默认语言
function updateDefaultLanguage() {
    blogI18nManager.updateDefaultLanguage();
}

// 更新翻译服务
function updateTranslationProvider() {
    blogI18nManager.updateTranslationProvider();
}

// 切换语言启用状态
function toggleLanguageEnabled(languageCode, enabled) {
    blogI18nManager.toggleLanguageEnabled(languageCode, enabled);
}

// 切换自动翻译
function toggleAutoTranslate(languageCode, autoTranslate) {
    blogI18nManager.toggleAutoTranslate(languageCode, autoTranslate);
}

// 管理博客多语言
function manageBlogI18n(blogId) {
    blogI18nManager.manageBlogI18n(blogId);
}

// 关闭多语言模态框
function closeI18nModal() {
    document.getElementById('i18n-modal').style.display = 'none';
}

// 保存多语言设置
async function saveI18nSettings() {
    // 实现保存逻辑
    blogI18nManager.showMessage('设置已保存', 'success');
    closeI18nModal();
}

// ==================== 多语言发布功能 ====================

// 多语言发布管理器
class BlogI18nPublisher {
    constructor() {
        this.supportedLanguages = [
            { code: 'zh-CN', name: '简体中文', enabled: true },
            { code: 'en-US', name: 'English', enabled: true },
            { code: 'ja-JP', name: '日本語', enabled: false },
            { code: 'ko-KR', name: '한국어', enabled: false }
        ];
        this.selectedLanguages = ['zh-CN', 'en-US'];
        this.selectedBlogId = null;
    }

    // 显示多语言发布模态框
    async showPublishModal() {
        const modal = document.getElementById('i18n-publish-modal');
        modal.style.display = 'block';
        
        // 加载博客列表
        await this.loadBlogList();
        
        // 渲染语言选项
        this.renderLanguageOptions();
        
        // 重置进度条
        this.resetProgress();
    }

    // 关闭多语言发布模态框
    closePublishModal() {
        const modal = document.getElementById('i18n-publish-modal');
        modal.style.display = 'none';
    }

    // 加载博客列表
    async loadBlogList() {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.get('/api/blogs?status=published');
            
            const select = document.getElementById('publish-blog-select');
            select.innerHTML = '<option value="">请选择要发布的博客文章</option>';
            
            if (response.success && response.data) {
                response.data.forEach(blog => {
                    const option = document.createElement('option');
                    option.value = blog._id;
                    option.textContent = blog.title;
                    select.appendChild(option);
                });
            }
            
            // 监听博客选择变化
            select.addEventListener('change', (e) => {
                this.selectedBlogId = e.target.value;
            });
            
        } catch (error) {
            console.error('加载博客列表失败:', error);
        }
    }

    // 渲染语言选项
    renderLanguageOptions() {
        const container = document.getElementById('publish-language-options');
        container.innerHTML = this.supportedLanguages.map(lang => `
            <div class="language-option ${lang.enabled ? '' : 'disabled'}">
                <input type="checkbox" id="publish-lang-${lang.code}" 
                       ${lang.enabled ? '' : 'disabled'} 
                       ${this.selectedLanguages.includes(lang.code) ? 'checked' : ''}
                       onchange="blogI18nPublisher.toggleLanguage('${lang.code}', this.checked)">
                <label for="publish-lang-${lang.code}">
                    ${lang.name} (${lang.code})
                </label>
                ${!lang.enabled ? '<span style="color: #999; font-size: 12px;">未启用</span>' : ''}
            </div>
        `).join('');
    }

    // 切换语言选择
    toggleLanguage(langCode, selected) {
        if (selected) {
            if (!this.selectedLanguages.includes(langCode)) {
                this.selectedLanguages.push(langCode);
            }
        } else {
            this.selectedLanguages = this.selectedLanguages.filter(l => l !== langCode);
        }
    }

    // 开始发布
    async startPublish() {
        if (!this.selectedBlogId) {
            alert('请选择要发布的博客文章');
            return;
        }
        
        if (this.selectedLanguages.length === 0) {
            alert('请至少选择一种发布语言');
            return;
        }

        // 显示进度条
        const progressContainer = document.getElementById('publish-progress');
        const progressFill = document.getElementById('progress-fill');
        const progressText = document.getElementById('progress-text');
        const startBtn = document.getElementById('start-publish-btn');
        
        progressContainer.style.display = 'block';
        startBtn.disabled = true;
        startBtn.textContent = '发布中...';

        try {
            // 1. 检查博客多语言状态
            progressText.textContent = '正在检查博客状态...';
            progressFill.style.width = '10%';
            
            const apiClient = new ApiClient();
            const statusResponse = await apiClient.get(`/api/blog-i18n/status/${this.selectedBlogId}`);
            
            if (!statusResponse.success) {
                throw new Error('获取博客状态失败');
            }
            
            // 2. 自动翻译内容
            const autoTranslate = document.getElementById('auto-translate').checked;
            if (autoTranslate && this.selectedLanguages.length > 1) {
                progressText.textContent = '正在翻译内容...';
                progressFill.style.width = '40%';
                
                const targetLanguages = this.selectedLanguages.filter(lang => lang !== 'zh-CN');
                if (targetLanguages.length > 0) {
                    await this.translateBlogContent(this.selectedBlogId, targetLanguages);
                }
            }
            
            // 3. 发布多语言版本
            progressText.textContent = '正在发布多语言版本...';
            progressFill.style.width = '70%';
            
            await this.publishI18nVersions(this.selectedBlogId);
            
            // 4. 完成
            progressText.textContent = '发布完成！';
            progressFill.style.width = '100%';
            
            setTimeout(() => {
                this.closePublishModal();
                alert('多语言博客发布成功！');
                // 刷新博客列表
                if (typeof blogManager !== 'undefined') {
                    blogManager.loadArticles();
                }
            }, 1000);
            
        } catch (error) {
            console.error('多语言发布失败:', error);
            progressText.textContent = '发布失败：' + error.message;
            progressFill.style.width = '100%';
            progressFill.classList.add('error');
            
            startBtn.disabled = false;
            startBtn.textContent = '重新发布';
        }
    }

    // 翻译博客内容
    async translateBlogContent(blogId, targetLanguages) {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.post(`/api/blog-i18n/translate/${blogId}`, {
                targetLanguages: targetLanguages
            });
            
            if (!response.success) {
                throw new Error('翻译失败');
            }
            
            return response.data.translations;
        } catch (error) {
            console.error('翻译博客内容失败:', error);
            throw error;
        }
    }

    // 发布多语言版本
    async publishI18nVersions(blogId) {
        try {
            const apiClient = new ApiClient();
            const response = await apiClient.post(`/api/blog-i18n/publish/${blogId}`, {
                languages: this.selectedLanguages
            });
            
            if (!response.success) {
                throw new Error('发布多语言版本失败');
            }
            
            return response.data;
        } catch (error) {
            console.error('发布多语言版本失败:', error);
            throw error;
        }
    }

    // 重置进度条
    resetProgress() {
        const progressContainer = document.getElementById('publish-progress');
        const progressFill = document.getElementById('progress-fill');
        const progressText = document.getElementById('progress-text');
        const startBtn = document.getElementById('start-publish-btn');
        
        progressContainer.style.display = 'none';
        progressFill.style.width = '0%';
        progressFill.classList.remove('error');
        progressText.textContent = '准备发布...';
        startBtn.disabled = false;
        startBtn.textContent = '开始发布';
    }
}

// 创建全局多语言发布器实例
const blogI18nPublisher = new BlogI18nPublisher();

// 初始化博客管理器
let blogManager;

// 初始化评论管理器
let commentManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    blogManager = new BlogManager();
    
    // 初始化多语言管理器
    setTimeout(() => {
        blogI18nManager.init();
    }, 1000);
});

// 将多语言管理器挂载到全局BlogManager对象上
BlogManager.refreshI18nConfig = refreshI18nConfig;
BlogManager.toggleI18nEnabled = toggleI18nEnabled;
BlogManager.updateDefaultLanguage = updateDefaultLanguage;
BlogManager.updateTranslationProvider = updateTranslationProvider;
BlogManager.toggleLanguageEnabled = toggleLanguageEnabled;
BlogManager.toggleAutoTranslate = toggleAutoTranslate;
BlogManager.manageBlogI18n = manageBlogI18n;
BlogManager.saveI18nSettings = saveI18nSettings;

// 将多语言发布器挂载到全局BlogManager对象上
BlogManager.showI18nPublishModal = function() {
    blogI18nPublisher.showPublishModal();
};

BlogManager.closeI18nPublishModal = function() {
    blogI18nPublisher.closePublishModal();
};

BlogManager.startI18nPublish = function() {
    blogI18nPublisher.startPublish();
};
